/*
 * Copyright (c) 2015 /5 /12
 * 	      7 :45 : 28
 *               By：wupeiji
 *               Q  Q：757671834
 * 	      It is not easy to meet each other in such a big world
 */

package com.security.security.service;

import com.security.model.user.User;
import com.security.model.user.UserRole;
import com.security.security.MyUserDetails;
import com.security.service.user.UserService;
import com.security.util.ValidateUtil;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service("managerDetialService")
public class ManagerDetialService implements UserDetailsService {
    private String TAG = "ManagerDetialService";
    @Resource
    private UserService userService;//与数据库操作的
    @Resource
    MyUserDetails userDetails = new MyUserDetails();

    public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException {

        User user = null;
        boolean isEmail = false;
        if(ValidateUtil.isMail(username)){
            user = userService.getUserByEmail(username);
            isEmail = true;
        }else{
            user = userService.getUserByMobile(username);
        }
        if (user != null) {
            //查到这个用户的话，进行认证吧
            System.out.println(TAG + "管理不空" + user.toString());
            userDetails.setPassword(user.getPassword());
            userDetails.setUsername(user.getMobile());
            userDetails.setEnabled(true);

            List<GrantedAuthority> authority = new ArrayList<GrantedAuthority>();
            Set<UserRole> roles = user.getRoles();
            if (roles == null) {
                roles = new HashSet<UserRole>();
            }
            for (UserRole sr : roles) {
                authority.add(new SimpleGrantedAuthority(sr.name()));
            }
            userDetails.setAuthorities(authority);

        }

        return userDetails;
    }
}
